﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using BEGDC.CC.Web.UserControls;
using BEGDC.CC.BL.CCFlow.CR;
using BEGDC.CC.Entity;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.BL.Common;
using BEGDC.Utility.Castle;
using BEGDC.CC.BL.Common.Query;

namespace BEGDC.CC.Web.Common
{
    /// <summary>
    /// Summary description for CustomerInput.
    /// </summary>
    public class CustomerInput : System.Web.UI.Page
    {
        #region Variables
        protected System.Web.UI.WebControls.TextBox Ctl_CustomerName;
        protected System.Web.UI.WebControls.TextBox Ctl_Title;
        protected System.Web.UI.WebControls.RadioButtonList Ctl_Gender;
        protected System.Web.UI.WebControls.Button Btn_Save;
        protected System.Web.UI.WebControls.Button Btn_Close;
        protected System.Web.UI.WebControls.TextBox Ctl_CompanyEN;
        protected System.Web.UI.WebControls.TextBox Ctl_CustomerNamePY;
        protected System.Web.UI.WebControls.TextBox Ctl_TitleEN;
        protected System.Web.UI.WebControls.TextBox Ctl_Company;
        //protected System.Web.UI.WebControls.TextBox tbReturnValue;
        protected System.Web.UI.WebControls.TextBox tbIsExist;
        protected System.Web.UI.WebControls.TextBox Ctl_Remark;
        //Search
        protected System.Web.UI.WebControls.Button ibtnSearch;
        protected System.Web.UI.WebControls.TextBox tbSearchName;
        protected System.Web.UI.WebControls.TextBox tbSearchTitle;
        protected System.Web.UI.WebControls.TextBox tbSearchCompany;
        protected System.Web.UI.WebControls.ImageButton btnPageLast;
        protected System.Web.UI.WebControls.ImageButton btnPageNext;
        protected System.Web.UI.WebControls.ImageButton btnPagePrev;
        protected System.Web.UI.WebControls.ImageButton btnPageFirst;
        protected System.Web.UI.WebControls.DataGrid DG_CustomerList;
        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            string RowIDStr = Request["RowID"];
            string StateStr = Request["State"];

            if (RowIDStr != null)
            {
                this.RowID = Convert.ToInt32(RowIDStr);
            }
            else
            {
                this.RowID = 0;
            }
            this.State = StateStr;

            if (!this.IsPostBack)
            {
                //this.Btn_Save.Attributes["onclick"] = "javascript:OnSave();";
                //this.Btn_Delete.Attributes["onclick"] = "javascript:OnDelete();";
                this.Btn_Close.Attributes["onclick"] = "javascript:OnClose();";
                //this.Btn_Save.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/bbw_ok.gif";
                //this.Btn_Delete.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/bbw_delete.gif";
                //this.Btn_Close.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/bbw_close.gif";
               // this.Ctl_CustomerName.Attributes.Add("readonly", "true");

                //this.Ctl_CustomerName.Attributes.Add("readonly", "true");
                //this.Ctl_CustomerNamePY.Attributes.Add("readonly", "true");
                //this.Ctl_Company.Attributes.Add("readonly", "true");
                //this.Ctl_CompanyEN.Attributes.Add("readonly", "true");

                if (this.RowID >= 0 && State == "Edit")
                {
                    //this.Btn_Delete.Visible = true;
                    InitForm();
                }
                else
                {
                    InitCustomerList(1);
                }
                //else
                //{
                //    InitFormFromSession();
                //}
            }

            //if(this.tbReturnValue.Text != string.Empty)
            //{
            //    string[] temp = this.tbReturnValue.Text.Split('|');
            //    this.Ctl_CustomerName.Text = temp[0];
            //    this.Ctl_Company.Text = temp[2];
            //    this.Ctl_Title.Text = temp[1];
            //    this.tbIsExist.Text = "1";

            //    this.tbReturnValue.Text = string.Empty;
            //}
        }

        #region RowID State
        protected int RowID
        {
            get { return (int)this.ViewState["CustomerRowID"]; }
            set { this.ViewState["CustomerRowID"] = value; }
        }
        protected string State
        {
            get { return this.ViewState["CustomerState"].ToString(); }
            set { this.ViewState["CustomerState"] = value; }
        }
        #endregion

        #region ObtainCustomerFromDataTable
        //		private DataRow ObtainCustomerFromDataTable(DataTable datatable)
        //		{
        //			if(datatable==null||datatable.Rows.Count==0||this.RowID<0) return null;
        //
        //			string IdStr = null;
        //			for(int i=0;i<datatable.Rows.Count;i++)
        //			{
        //                 IdStr = datatable.Rows[i]["Id"].ToString();
        //				 int IdInt = Convert.ToInt32(IdStr);
        //				if(IdInt==this.AttendeeID)
        //				{
        //					return datatable.Rows[i];
        //				}
        //			}
        //			return null;
        //		}
        #endregion

        #region InitForm
        private void InitForm()
        {
            //			ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
            //			BEGDC.CC.Entity.CustomerAttendee customer = CRService.GetCustomerAttendee(this.AttendeeID);
            //
            //			if(customer!=null)
            //			{
            //				this.Ctl_CustomerName.Text = customer.NameEN;
            //				this.Ctl_Title.Text = customer.Title;
            //				if(customer.Gender)
            //				{
            //				    this.Ctl_Gender.Items[0].Selected = true;
            //				}
            //				else
            //				{
            //					this.Ctl_Gender.Items[1].Selected = true;
            //				}
            //				this.Ctl_Remark.Text = customer.Remark;
            //			}

            DataTable CustomerDataTable = null;
            DataRow CustomerRow = null;
            object SessCustomerAttendee = Session[SessionFlag.CustomerSession];
            if (SessCustomerAttendee != null)
            {
                InitCustomerList(1);
                CustomerDataTable = (DataTable)SessCustomerAttendee;
            }
            else
            {
                InitCustomerList(1);
                return;
            }

            if (this.RowID >= 0)
            {
                CustomerRow = CustomerDataTable.Rows[this.RowID];

                this.Ctl_CustomerName.Text = CustomerRow["NameCN"].ToString();
                this.Ctl_Title.Text = CustomerRow["Title"].ToString();
                this.Ctl_Company.Text = CustomerRow["Company"].ToString();
                this.Ctl_CustomerNamePY.Text = CustomerRow["Name"].ToString();
                this.Ctl_TitleEN.Text = CustomerRow["TitleEN"].ToString();
                this.Ctl_CompanyEN.Text = CustomerRow["CompanyEN"].ToString();
                this.tbIsExist.Text = CustomerRow["IsExisted"].ToString();


                if (CustomerRow["Gender"].ToString().Trim() == "True")
                {
                    this.Ctl_Gender.Items.FindByValue("1").Selected = true;
                }
                else
                {
                    this.Ctl_Gender.Items.FindByValue("0").Selected = true;
                }
                this.Ctl_Remark.Text = CustomerRow["Remark"].ToString();
            }
        }
        #endregion

        //private void InitFormFromSession()
        //{
        //    DataTable contractInfo = null;
        //    DataRow row = null;
        //    object sessContractInfo = Session[SessionFlag.CustomerSession];
        //    if (sessContractInfo != null)
        //    {
        //        contractInfo = (DataTable)sessContractInfo;
        //    }
        //    else
        //    {
        //        return;
        //    }

        //    if (contractInfo.Rows.Count > 0)
        //    {
        //        row = contractInfo.Rows[contractInfo.Rows.Count - 1];

        //        this.Ctl_Title.Text = row["Title"].ToString();
        //        this.Ctl_Company.Text = row["Company"].ToString();

        //        this.Ctl_TitleEN.Text = row["TitleEN"].ToString();
        //        this.Ctl_CompanyEN.Text = row["CompanyEN"].ToString();
        //    }
        //}

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Btn_Save.Click += new EventHandler(Btn_Save_Click);
            this.ibtnSearch.Click += new EventHandler(SearchBtn_Click);
            this.btnPageFirst.Click += new System.Web.UI.ImageClickEventHandler(this.PageFirstBtn_Click);
            this.btnPagePrev.Click += new System.Web.UI.ImageClickEventHandler(this.PagePrevBtn_Click);
            this.btnPageNext.Click += new System.Web.UI.ImageClickEventHandler(this.PageNextBtn_Click);
            this.btnPageLast.Click += new System.Web.UI.ImageClickEventHandler(this.PageLastBtn_Click);
            this.DG_CustomerList.ItemDataBound += new DataGridItemEventHandler(DG_CustomerList_ItemDataBound);
            this.DG_CustomerList.PageIndexChanged += new DataGridPageChangedEventHandler(DG_CustomerList_PageIndexChanged);
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion

        #region Update Customer Session
        private void UpdateCustomerSession()
        {
            DataTable CustomerDataTable = null;
            DataRow CustomerRow = null;
            object SessCustomerAttendee = Session[SessionFlag.CustomerSession];
            if (SessCustomerAttendee != null)
            {
                CustomerDataTable = (DataTable)SessCustomerAttendee;
            }
            else
            {
                Response.Write("<script>alert('The session is missed, please reopen the application! 丢失 Session, 请重新申请!')</script>");
                return;
            }

            IQuery QueryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            bool IsCustomerExisted = QueryService.IsExistedCustomer(this.Ctl_CompanyEN.Text, this.Ctl_CustomerNamePY.Text, this.Ctl_TitleEN.Text);
            if (!IsCustomerExisted && this.State != "Delete")
            {
                //Page.RegisterClientScriptBlock("","<script>alert('The Customer is not in CIS!');</script>");
                WebUtility.ShowAlert(this.Page, "The customer you are saving does not exist in CIS. 正在保存的客户不在CIS系统中!");
            }
            if (this.State == "New")
            {
                //if (CustomerDataTable.Select("NameCN='" + this.Ctl_CustomerName.Text.Trim() + "' And Company='" + this.Ctl_Company.Text.Trim() + "' And Title='" + this.Ctl_Title.Text.Trim() + "'").Length > 0)
                if (CustomerDataTable.Select("Name='" + this.Ctl_CustomerNamePY.Text.Trim() + "' And CompanyEN='" + this.Ctl_CompanyEN.Text.Trim() + "' And TitleEN='" + this.Ctl_TitleEN.Text.Trim() + "'").Length > 0)
                {
                    Response.Write("<script>alert('This person is already in the list. 该客户已经存在列表中！')</script>");
                    return;
                }

                CustomerRow = CustomerDataTable.NewRow();

                CustomerRow["Id"] = "0";
                CustomerRow["Name"] = this.Ctl_CustomerNamePY.Text.Trim();
                CustomerRow["Title"] = this.Ctl_Title.Text.Trim();
                CustomerRow["Company"] = this.Ctl_Company.Text.Trim();
                CustomerRow["NameCN"] = this.Ctl_CustomerName.Text.Trim();
                CustomerRow["TitleEN"] = this.Ctl_TitleEN.Text.Trim();
                CustomerRow["CompanyEN"] = this.Ctl_CompanyEN.Text.Trim();

                int Gender = Convert.ToInt32(this.Ctl_Gender.SelectedValue);
                CustomerRow["Gender"] = (Gender == 1) ? true : false;
                CustomerRow["Remark"] = this.Ctl_Remark.Text;
                if (IsCustomerExisted)
                {
                    CustomerRow["IsExisted"] = BEGDC.CC.BL.Common.CISFlag.Existed;
                }
                else
                {
                    CustomerRow["IsExisted"] = BEGDC.CC.BL.Common.CISFlag.NotExisted;
                }

                CustomerDataTable.Rows.Add(CustomerRow);
            }
            else if (this.State == "Edit" && this.RowID >= 0)
            {
                //CustomerRow = ObtainCustomerFromDataTable(CustomerDataTable);
                CustomerRow = CustomerDataTable.Rows[this.RowID];

                CustomerRow["Name"] = this.Ctl_CustomerNamePY.Text;
                CustomerRow["Title"] = this.Ctl_Title.Text;
                CustomerRow["Company"] = this.Ctl_Company.Text;
                CustomerRow["NameCN"] = this.Ctl_CustomerName.Text;
                CustomerRow["TitleEN"] = this.Ctl_TitleEN.Text;
                CustomerRow["CompanyEN"] = this.Ctl_CompanyEN.Text;

                int Gender = Convert.ToInt32(this.Ctl_Gender.SelectedValue);
                CustomerRow["Gender"] = (Gender == 1) ? true : false;
                CustomerRow["Remark"] = this.Ctl_Remark.Text;
                if (IsCustomerExisted)
                {
                    CustomerRow["IsExisted"] = BEGDC.CC.BL.Common.CISFlag.Existed;
                }
                else
                {
                    CustomerRow["IsExisted"] = BEGDC.CC.BL.Common.CISFlag.NotExisted;
                }
            }
            else if (this.State == "Delete" && this.RowID >= 0)
            {
                CustomerDataTable.Rows.RemoveAt(this.RowID);
            }
            else
            {
                return;
            }

            Session[SessionFlag.CustomerSession] = CustomerDataTable;

            //			ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
            //			BEGDC.CC.Entity.CustomerAttendee customer = CRService.GetCustomerAttendeeInfo(this.CustomerID);
            //
            //			if(customer==null)
            //			{
            //				customer = new BEGDC.CC.Entity.CustomerAttendee();
            //				BEGDC.CC.Entity.CustomerInfo customerInfo = CRService.GetCustomerInfo(customer.CustomerInfo.Id);
            //				if(customerInfo!=null)
            //				{
            //					customer.CustomerInfo = customerInfo;
            //				}
            //				else
            //				{
            //					return null;
            //				}
            //			}
            //
            //			customer.NameEN = this.Ctl_CustomerName.Text;
            //			customer.Title = this.Ctl_Title.Text;
            //			int Gender = Convert.ToInt32(this.Ctl_Gender.SelectedValue);
            //			customer.Gender = (Gender==1) ? true : false;
            //			customer.Remark = this.Ctl_Remark.Text;
            //
            //			return customer;
        }
        #endregion

        #region Save
        void Btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                UpdateCustomerSession();
            }
            catch (Exception exp)
            {
                throw exp;
            }
            Response.Write("<script>window.close();window.returnValue='reload';</script>");
        }
        #endregion

        #region Delete
        //		private void Btn_Delete_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        //		{
        //			try
        //			{
        //				this.State = "Delete";
        //				UpdateCustomerSession();
        //			}
        //			catch(Exception exp)
        //			{
        //				throw exp;
        //			}
        //			Response.Write("<script>window.close();window.returnValue='reload';</script>");
        //		}
        #endregion


        #region Search

        void SearchBtn_Click(object sender, EventArgs e)
        {
            if (this.tbSearchName.Text == "" && this.tbSearchTitle.Text == "" && this.tbSearchCompany.Text == "")
            {
                Page.RegisterClientScriptBlock("", "<script>alert('Please specify information about the customer. 请输入客户信息的查询条件!');</script>");
                return;
            }
            else
            {
                //this.btnPageFirst.Visible = true;
                //this.btnPageLast.Visible = true;
                //this.btnPageNext.Visible = true;
                //this.btnPagePrev.Visible = true;
                InitForm(1);
            }
        }

        private void InitCustomerList(int pageIndex)
        {
            bool IsDomestic = true;

            IQuery QueryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            DataTable CISSource = QueryService.GetCustomerFromCIS(string.Empty, string.Empty, string.Empty, IsDomestic);

            int count = CISSource.DefaultView.Count;
            this.DG_CustomerList.DataSource = CISSource.DefaultView;
            this.DG_CustomerList.DataBind();

            SetPageCount(count, pageIndex);
        }

        private void InitForm(int pageIndex)
        {
            string CISName = this.tbSearchName.Text;
            string CISTitle = this.tbSearchTitle.Text;
            string CISCompany = this.tbSearchCompany.Text;
            bool IsDomestic = true;

            IQuery QueryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            DataTable CISSource = QueryService.GetCustomerFromCIS(CISName, CISTitle, CISCompany, IsDomestic);

            int count = CISSource.DefaultView.Count;
            this.DG_CustomerList.DataSource = CISSource.DefaultView;
            this.DG_CustomerList.DataBind();

            SetPageCount(count, pageIndex);
        }

        private void SetPageCount(int count, int pageIndex)
        {
            if (count > 0)
            {
                _RowCount = count;
                _PageCount = count / this.DG_CustomerList.PageSize;
                if (count % this.DG_CustomerList.PageSize > 0) _PageCount++;

                _CurrentPageIndex = pageIndex;
                SetPageNavi(pageIndex);
            }
            else
            {
                _RowCount = count;
                _PageCount = count;
                _CurrentPageIndex = 0;
                SetPageNavi(0);
            }
        }

        #endregion

        #region page navigation
        private int _PageCount
        {
            get
            {
                if (ViewState["PageCount"] != null) return (int)ViewState["PageCount"];
                else
                    return 0;
            }
            set
            {
                ViewState["PageCount"] = value;
            }
        }
        private int _CurrentPageIndex
        {
            get
            {
                if (ViewState["CurrentPageIndex"] != null) return (int)ViewState["CurrentPageIndex"];
                else
                    return 0;
            }
            set
            {
                ViewState["CurrentPageIndex"] = value;
            }
        }
        private int _RowCount
        {
            get
            {
                if (ViewState["RowCount"] != null) return (int)ViewState["RowCount"];
                else
                    return 0;
            }
            set
            {
                ViewState["RowCount"] = value;
            }
        }

        private void SetPageNavi(int newPage)
        {
            if (newPage <= 1)
            {
                this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_first_inact.gif";
                this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_pre_inact.gif";
                this.btnPageFirst.Attributes["disabled"] = "true";
                this.btnPagePrev.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_first.gif";
                this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_pre.gif";
                this.btnPageFirst.Attributes.Remove("disabled");
                this.btnPagePrev.Attributes.Remove("disabled");
            }

            if (newPage >= _PageCount)
            {
                this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_next_inact.gif";
                this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_last_inact.gif";
                this.btnPageNext.Attributes["disabled"] = "true";
                this.btnPageLast.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_next.gif";
                this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_last.gif";
                this.btnPageNext.Attributes.Remove("disabled");
                this.btnPageLast.Attributes.Remove("disabled");
            }
        }

        #endregion

        #region CustomerList_PageIndexChanged

        void DG_CustomerList_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            try
            {
                //SetCheckedProjectList();
                this.DG_CustomerList.CurrentPageIndex = e.NewPageIndex;
                this.InitForm(e.NewPageIndex);
            }
            catch
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        #endregion

        #region ---------- paging events ----------------
        private void PageFirstBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.DG_CustomerList.CurrentPageIndex = 0;
            this.InitForm(1);
        }

        private void PagePrevBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (_CurrentPageIndex == 1) return;
            this.DG_CustomerList.CurrentPageIndex = _CurrentPageIndex - 2;
            this.InitForm(_CurrentPageIndex - 1);
        }

        private void PageNextBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (_CurrentPageIndex == _PageCount) return;
            this.DG_CustomerList.CurrentPageIndex = _CurrentPageIndex;
            this.InitForm(_CurrentPageIndex + 1);
        }

        private void PageLastBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.DG_CustomerList.CurrentPageIndex = _PageCount - 1;
            this.InitForm(_PageCount);
        }
        #endregion

        void DG_CustomerList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                e.Item.Attributes.Add("onclick ", "test(this); ");
                e.Item.ID = "ItemID ";
                e.Item.Cells[1].Text = e.Item.Cells[1].Text.Replace(" ", "&nbsp;");
                e.Item.Cells[3].Text = e.Item.Cells[3].Text.Replace(" ", "&nbsp;");
            }
        }
    }
}
